package com.hz.ruoyimqttconsume.scheduled;

import com.alibaba.fastjson.JSON;
import com.hz.ruoyimqttconsume.mapper.EqCountMapper;
import com.hz.ruoyimqttconsume.utils.LatestDataCache;
import com.ruoyi.system.api.EquipmentService;
import com.ruoyi.system.api.domain.CqTimeData;
import com.ruoyi.system.api.domain.QxTimeData;
import com.ruoyi.system.api.domain.SoilTimeData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author 侯文波
 * @date 2025/3/12 18:43
 * @description:
 */
@Component
@Slf4j
public class MQTTMessageScheduledTasks {

    @Autowired
    private EqCountMapper eqCountMapper;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private  LatestDataCache dataCache;

    /**
     * 12点插入 pest 数据
     * @throws MessagingException
     */
    @Scheduled(cron = "0 0 12 * * ?")
    public void handlePestMessage() throws MessagingException {
        int count = eqCountMapper.eqCount("虫情监测站");
        for (int i = 0; i < count; i++){
            Object data = dataCache.getLatestPestData();
            if (data != null){
                CqTimeData cqTimeData = JSON.parseObject(data.toString(), CqTimeData.class);
                equipmentService.insertCq(cqTimeData);
            }
        }
    }

    /**
     * 每小时插入 soil 数据
     * @throws MessagingException
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void handleSoilMessage() throws MessagingException {
        int count = eqCountMapper.eqCount("土壤墒情站");
        for (int i = 0; i < count; i++){
            Object data = dataCache.getLatestSoilData();
            if (data != null){
                SoilTimeData soilTimeData = JSON.parseObject(data.toString(), SoilTimeData.class);
                equipmentService.insertSoil(soilTimeData);
            }
        }
    }

    /**
     * 每小时插入 environmental 数据
     * @throws MessagingException
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void handleEnvironmentalMessage() throws MessagingException {
        int count = eqCountMapper.eqCount("气象站");
        for (int i = 0; i < count; i++){
            Object data = dataCache.getLatestEnvData();
            if (data != null){
                QxTimeData qxTimeData = JSON.parseObject(data.toString(), QxTimeData.class);
                equipmentService.insertQx(qxTimeData);
            }
        }
    }


}
